<?php
declare(strict_types=1);
/**
 * Created by project.
 * Act23: huanzipap
 * Date: 2023/12/27
 * Time: 11:25
 */
namespace App\Middleware;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

//引入
use Hyperf\Contract\SessionInterface;
use App\Libs\ReMsg;

class AdminApiAuth implements MiddlewareInterface
{
    protected ContainerInterface $container;
    protected RequestInterface $request;
    protected HttpResponse $response;

    #[Inject] protected SessionInterface $session;
    #[Inject] protected ReMsg $reMsg;

    protected string|null $app_env;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
        $this->app_env = config('app_name').'-'.config('app_env');
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        //虚拟数据
//        $api_admin = new \stdClass();
//        $api_admin->id = 1;
//        $api_admin->username = 'admin';
//        $api_admin->phone = '18888888888';
//        $api_admin->level = 1;
//        $api_admin->party_id = null;
//        $api_admin->app_env = $this->app_env;
//        $this->session->set('api_admin', $api_admin);
//        $this->session->save();
        //虚拟数据

        //获取用户session信息
        $loginAdmin = $this->session->get('api_admin',null);
        if (empty($loginAdmin) || !isset($loginAdmin->app_env) || $loginAdmin->app_env!=$this->app_env) {
            return $this->reMsg->re(10002);
        } else {
            return $handler->handle($request);
        }
    }
}